package com.milo.controller;

import com.milo.service.IConsumerService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author: Milogenius
 * @create: 2019-06-28 13:45
 * @description:
 **/
@RestController
@Slf4j
public class ConsumerController {

    @Autowired
    private IConsumerService consumerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod = "queryPortFail")
    public String index(@RequestParam String name){
        return  consumerService.hello(name);
    }


    /**
     * 回滚方法
     * <p>
     *     注意:方法参数一定要和api方法一致
     * </p>
     * @param name
     * @return
     */
    private String queryFortFail(String name){
        //服务预警机制
        String redisKey = "Server_Port_Cache";
        String s = redisTemplate.opsForValue().get(redisKey);
        //异步处理
        new Thread(()->{
            if (StringUtils.isEmpty(s)) {
                log.info("未发生短信,通知相关人员,服务异常");
                redisTemplate.opsForValue().set(redisKey,"服务异常,请核实",20, TimeUnit.SECONDS);
            } else {
                log.info("已经发送过短信,无需发送短信");
            }
        }).start();


        return "网络异常,请稍后再试";
    }
}
